package com.katze.common.socket.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.OutputStream;
import java.net.BindException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.function.Consumer;

public class SocketServerThread extends Thread {

    private static final Logger log = LoggerFactory.getLogger(SocketServerThread.class);

    private volatile boolean exit = false;

    private final int port;

    private final Consumer<Socket> task;

    public SocketServerThread(int port, Consumer<Socket> task) {
        this.port = port;
        this.task = task;
        setName(port + "-SocketServerThread");
    }

    @Override
    public void run() {
        try (ServerSocket server = new ServerSocket(this.port)) {
            while (!exit) {
                try {
                    task.accept(server.accept());
                } catch (Exception e) {
                    log.error("通讯服务{}端口接收异常", this.port, e);
                }
            }
        } catch (BindException e) {
            log.error("通讯服务{}端口已被占用", this.port, e);
        } catch (Throwable e) {
            log.error("通讯服务{}端口处理异常", this.port, e);
        } finally {
            log.info("通讯服务{}端口关闭成功", this.port);
        }
    }

    public void exit() {
        this.exit = true;
        try (Socket socket = new Socket("127.0.0.1", port); OutputStream out = socket.getOutputStream();){
            out.write("kill".getBytes());
        } catch (ConnectException ignored){} catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
